-module(active_record).

-include_lib("eunit/include/eunit.hrl").
-include_lib("stdlib/include/qlc.hrl").

-include("records.hrl").

-export([create/1, find/1, in_test_db/1]).

create(ToBeCreated) ->
	F = fun() -> mnesia:write(ToBeCreated) end,
	Result = mnesia:transaction(F),
	log:debug("CREATION FINISHED: ~w~n", [Result]),
	ToBeCreated.

find(Query) -> 
	F = fun() -> qlc:e(Query) end,
    mnesia:transaction(F).

% Test methods

start_db() -> 
	mnesia:delete_schema([node()]),
	mnesia:create_schema([node()]),
	mnesia:start().

stop_db() -> 
	mnesia:stop().

create_schema() ->
    mnesia:create_table(branch, [{attributes, record_info(fields, branch)}]),
    mnesia:create_table(troop, [{attributes, record_info(fields, troop)}]),
    mnesia:create_table(army, [{attributes, record_info(fields, army)}]),
    mnesia:create_table(city, [{attributes, record_info(fields, city)}]).

in_test_db(Fun) ->
	start_db(),
	create_schema(),
	Result = Fun(),
	stop_db(),
	Result.

% Tests

general_process_test_() ->
	start_db(),
	Result = create_schema(),
	stop_db(),
	[
	?_assertMatch({atomic,ok}, Result)
	].
